"""
简单修复景点图片显示问题
"""
import time
from django.core.management.base import BaseCommand
from django.conf import settings
from apps.attractions.models import Attraction
from utils.amap_client import AMapClient


class Command(BaseCommand):
    help = '简单修复景点图片显示问题'

    def handle(self, *args, **options):
        self.stdout.write('开始修复景点图片...')

        # 1. 检查当前数据状态
        total = Attraction.objects.count()
        with_images = Attraction.objects.filter(
            amap_image_urls__isnull=False
        ).exclude(amap_image_urls=[]).count()

        self.stdout.write(f'总景点数: {total}')
        self.stdout.write(f'有图片的景点数: {with_images}')

        # 2. 如果有景点没有图片，尝试获取
        if with_images < total:
            self.stdout.write('发现没有图片的景点，开始获取...')

            api_key = settings.AMAP_CONFIG.get('API_KEY')
            if not api_key:
                self.stdout.write(self.style.ERROR('没有API Key，跳过获取'))
                return

            amap_client = AMapClient(api_key)

            # 获取没有图片的景点
            no_images = Attraction.objects.filter(
                amap_poi_id__isnull=False
            ).exclude(amap_poi_id='').filter(
                amap_image_urls__isnull=True
            ) | Attraction.objects.filter(
                amap_poi_id__isnull=False
            ).exclude(amap_poi_id='').filter(amap_image_urls=[])

            self.stdout.write(f'需要处理的景点: {no_images.count()}')

            for attr in no_images[:10]:  # 只处理前10个
                try:
                    self.stdout.write(f'处理: {attr.name}')

                    time.sleep(0.5)
                    poi_detail = amap_client.get_poi_detail(attr.amap_poi_id)

                    if poi_detail.get('status') == '1' and poi_detail.get('pois'):
                        poi = poi_detail['pois'][0]
                        photos = poi.get('photos', [])

                        image_urls = []
                        for photo in photos[:5]:
                            if isinstance(photo, dict):
                                url = photo.get('url') or photo.get('src')
                                if url and isinstance(url, str):
                                    if not url.startswith('http'):
                                        if url.startswith('//'):
                                            url = 'https:' + url
                                        elif url.startswith('/'):
                                            url = 'https://restapi.amap.com' + url
                                    if url.startswith('http'):
                                        image_urls.append(url)

                        if image_urls:
                            attr.amap_image_urls = image_urls
                            attr.save(update_fields=['amap_image_urls'])
                            self.stdout.write(f'  ✓ 获取 {len(image_urls)} 张图片')

                except Exception as e:
                    self.stdout.write(f'  ✗ 失败: {str(e)}')

        self.stdout.write('修复完成！请刷新前端页面查看效果。')
